package com.youdoneed.community.forum.web;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.youdoneed.community.forum.service.AllowviewmessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.youdoneed.base.application.ResultMessage;
import com.youdoneed.base.common.JWTUtils;
import com.youdoneed.community.forum.entity.Forumuserattentionanotherrel;
import com.youdoneed.community.forum.service.ForumuserattentionanotherrelService;
import com.youdoneed.user.feign.UserFeignClient;
import com.youdoneed.user.model.User;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 通讯录关注模块请求控制器
 *
 * @author shum
 * @date 2017.6.12
 */
@RestController
@RequestMapping(value = "/forumuserattentionanotherrel")
@Api(value = "用户关注模块请求控制器", description = "用户关注模块请求控制器")
public class ForumuserattentionanotherrelController {

    private static final Logger logger = LoggerFactory.getLogger(ForumuserattentionanotherrelController.class);
    @Autowired
    ForumuserattentionanotherrelService forumuserattentionanotherrelService;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private AllowviewmessageService allowviewmessageService;

    @RequestMapping(value = "/getMyAttentionUsers", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "查询我关注的用户", value = "查询我关注的用户")
    public ResultMessage<List<String>> getMyAttentionUsers(@RequestHeader("Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        List<String> listUserId = forumuserattentionanotherrelService.getMyAttentionUsers(userId);
        if (null != listUserId) {
            return new ResultMessage<List<String>>(listUserId).toSuccess("查询我关注的用户成功！");
        }
        return new ResultMessage<List<String>>(null).toFailure("查询我关注的用户失败！");
    }

    @RequestMapping(value = "/isFocusOrNot", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "查询是否关注", value = "查询是否关注")
    public ResultMessage<String> isFocusOrNot(@ApiParam("用户id") @RequestParam String userId,
                                              @ApiParam("被关注用户id") @RequestParam String friendId) {
        Forumuserattentionanotherrel record = new Forumuserattentionanotherrel();
        record.setUserId(userId);
        record.setAttentionedUserId(friendId);
        Forumuserattentionanotherrel AttentionList = forumuserattentionanotherrelService.findAttentionByUserIdFriendId(record);
        if (null != AttentionList) {
            return new ResultMessage<String>("true");
        } else {
            return new ResultMessage<String>("false");
        }
    }

    @RequestMapping(value = "/findUserAttention", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "后台查询我的关注/我被关注", value = "后台查询我的关注/我被关注")
    public ResultMessage<List<Forumuserattentionanotherrel>> findUserAttention(@ApiParam("查询类型：0（我的关注），1（我被关注）") @RequestParam String type,
                                                                               @ApiParam("当前页码") @RequestParam(required = false) String currentPage,
                                                                               @ApiParam("每页显示的记录条数") @RequestParam(required = false) String rows,
                                                                               @RequestHeader("Authorization") String token) {
        logger.info("后台查询我的关注/我被关注");
        String userId = JWTUtils.getTokenUserId(token);
        Forumuserattentionanotherrel record = new Forumuserattentionanotherrel();
        if ("0".equals(type)) {
            record.setUserId(userId);
        } else if ("1".equals(type)) {
            record.setAttentionedUserId(userId);
        }

        if (!StringUtils.hasText(currentPage)) {
            currentPage = "1";
        }
        if (!StringUtils.hasText(rows)) {
            rows = "10";
        }
        return new ResultMessage<>(forumuserattentionanotherrelService.findAttention(record, currentPage, rows));
    }

    @RequestMapping(value = "/saveUserAttention", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "加关注", value = "加关注")
    public ResultMessage<String> saveUserAttention(@ApiParam("被关注的用户id") @RequestParam String attentionedUserId,
                                                   @ApiParam("要关注的用户id") @RequestParam String userId) {
        logger.info("加关注");
        Forumuserattentionanotherrel record = new Forumuserattentionanotherrel();
        record.setUserId(userId);
        record.setAttentionedUserId(attentionedUserId);
        Forumuserattentionanotherrel AttentionList = forumuserattentionanotherrelService.findAttentionByUserIdFriendId(record);
        if (null != AttentionList) {
            return new ResultMessage<String>().toFailure("关注失败，该用户您已经关注过！");
        } else {
            if (forumuserattentionanotherrelService.save(record))
                return new ResultMessage<String>().toSuccess("关注成功！");
            else
                return new ResultMessage<String>().toFailure("关注失败！");
        }

    }

    /**
     * 批量保存关注信息
     * @param userId
     * @return
     * @author lid
     * @date 2017.12.26
     */
    @RequestMapping(value = "/saveAttentionInBatch", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "批量加关注", value = "批量加关注")
    public ResultMessage<?> saveAttentionInBatch(@ApiParam("用户id") @RequestParam String userId,
                                                 @ApiParam("好友id") @RequestBody List<String> friendIds) {
        forumuserattentionanotherrelService.saveAttentionInBatch(userId, friendIds);
        return new ResultMessage<String>().toSuccess("批量保存关注成功！");
    }

    @RequestMapping(value = "/deleteUserAttention", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "取消关注", value = "取消关注")
    public ResultMessage<String> deleteUserAttention(@ApiParam("要取消被关注的用户id") @RequestParam String attentionedUserId,
                                                     @RequestHeader("Authorization") String token) {
        logger.info("取消关注");
        String userId = JWTUtils.getTokenUserId(token);
        Forumuserattentionanotherrel record = new Forumuserattentionanotherrel();
        record.setUserId(userId);
        record.setAttentionedUserId(attentionedUserId);
        Forumuserattentionanotherrel attentionList = forumuserattentionanotherrelService.findAttentionByUserIdFriendId(record);
        if (null == attentionList) {
            return new ResultMessage<String>().toFailure("取消关注失败，该用户您没有关注过！");
        } else {
            if (forumuserattentionanotherrelService.delete(attentionList.getForumUserAttentionAnotherRelId())){
                //删除帖子可见记录，A取消关注B，A不再看到B的帖子
                allowviewmessageService.deleleByUserIds(userId, attentionedUserId);
                return new ResultMessage<String>().toSuccess("取消关注成功！");
            }else{
                return new ResultMessage<String>().toFailure("取消关注失败！");
            }

        }
    }

    @RequestMapping(value = "/deleteUserAttentionForFriends", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "取消关注(后台调用)", value = "取消关注(后台调用)")
    public ResultMessage<String> deleteUserAttentionForFriends(@ApiParam("要取消被关注的用户id") @RequestParam String attentionedUserId,
                                                               @ApiParam("要取消关注的用户id") @RequestParam String userId) {
        logger.info("取消关注");
        Forumuserattentionanotherrel record = new Forumuserattentionanotherrel();
        record.setUserId(userId);
        record.setAttentionedUserId(attentionedUserId);
        Forumuserattentionanotherrel attentionList = forumuserattentionanotherrelService.findAttentionByUserIdFriendId(record);
        if (null == attentionList) {
            return new ResultMessage<String>().toFailure("取消关注失败，该用户您没有关注过！");
        } else {
            if (forumuserattentionanotherrelService.delete(attentionList.getForumUserAttentionAnotherRelId()))
                return new ResultMessage<String>().toSuccess("取消关注成功！");
            else
                return new ResultMessage<String>().toFailure("取消关注失败！");
        }
    }

    @RequestMapping(value = "/findRecommendAttention", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "推荐关注", value = "推荐关注")
    public ResultMessage<List<Map<String, Object>>> findRecommendAttention(
            @ApiParam("当前页码") @RequestParam(required = false) Integer currentPage,
            @ApiParam("每页显示的记录条数") @RequestParam(required = false) Integer rows,
            @RequestHeader("Authorization") String token) {
        logger.info("推荐关注");
        String userId = JWTUtils.getTokenUserId(token);
        if (currentPage == null) {
            currentPage = 1;
        }
        if (rows == null) {
            rows = 10;
        }
        List<Forumuserattentionanotherrel> attention = forumuserattentionanotherrelService.findRecommendAttention(userId, currentPage, rows);
        String[] attentionUserIds = new String[attention.size()];
        for (int i = 0; i < attention.size(); i++) {
            attentionUserIds[i] = attention.get(i).getUserId();
        }
        List<User> attentionUserlist = userFeignClient.getUsers(attentionUserIds).getData();
        List<Map<String, Object>> attentionList = new ArrayList<Map<String, Object>>();

        for (int j = 0; j < attentionUserlist.size(); j++) {
            Map<String, Object> attentionMap = new HashMap<String, Object>();
            attentionMap.put("user", attentionUserlist.get(j));
            for (int i = 0; i < attention.size(); i++) {
                if (attention.get(i).getUserId().equals(attentionUserlist.get(j).getUserId())) {
                    attentionMap.put("countFocus", attention.get(i).getCountFocus());
                    break;
                }
            }
            attentionList.add(attentionMap);
        }

        //根据相似度降序排序
        Collections.sort(attentionList, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                if ((int) o1.get("countFocus") < (int) o2.get("countFocus")) {
                    return 1;
                }
                if ((int) o1.get("countFocus") == (int) o2.get("countFocus")) {
                    return 0;
                }
                return -1;
            }
        });
        return new ResultMessage<>(attentionList);
    }



}
